package com.example.demoforscrollconflict

import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import android.widget.FrameLayout
import androidx.core.view.NestedScrollingChild3
import androidx.core.view.NestedScrollingChildHelper
import androidx.core.view.NestedScrollingParent3
import androidx.core.view.NestedScrollingParentHelper
import androidx.core.view.ViewCompat
import androidx.recyclerview.widget.RecyclerView

/**
 * 滑动冲突处理示例集合
 * 包含各种常见的滑动冲突场景和解决方案
 */
class ScrollConflictExamples {

    /**
     * 示例1：嵌套RecyclerView滑动冲突处理
     * 通过重写onInterceptTouchEvent来判断是否拦截子View的触摸事件
     */
    class NestedRecyclerView @JvmOverloads constructor(
        context: Context,
        attrs: AttributeSet? = null,
        defStyleAttr: Int = 0
    ) : RecyclerView(context, attrs, defStyleAttr) {

        private var startY = 0f
        private var startX = 0f
        private var isVerticalScroll = false

        override fun onInterceptTouchEvent(ev: MotionEvent?): Boolean {
            ev?.let { event ->
                when (event.action) {
                    MotionEvent.ACTION_DOWN -> {
                        startY = event.y
                        startX = event.x
                        isVerticalScroll = false
                    }
                    MotionEvent.ACTION_MOVE -> {
                        val deltaY = Math.abs(event.y - startY)
                        val deltaX = Math.abs(event.x - startX)
                        
                        // 如果垂直滑动距离大于水平滑动距离，且大于阈值，则拦截事件
                        if (deltaY > deltaX && deltaY > 10) {
                            isVerticalScroll = true
                        }
                    }
                }
            }
            return super.onInterceptTouchEvent(ev)
        }

        override fun onTouchEvent(event: MotionEvent?): Boolean {
            // 处理触摸事件
            return super.onTouchEvent(event)
        }
    }

    /**
     * 示例2：ViewPager2与RecyclerView水平滑动冲突处理
     * 使用嵌套滚动机制来解决冲突
     */
    class HorizontalScrollConflictLayout @JvmOverloads constructor(
        context: Context,
        attrs: AttributeSet? = null,
        defStyleAttr: Int = 0
    ) : FrameLayout(context, attrs, defStyleAttr), NestedScrollingParent3 {

        private val parentHelper = NestedScrollingParentHelper(this)
        private var startX = 0f
        private var startY = 0f
        private var isHorizontalScroll = false

        override fun onInterceptTouchEvent(ev: MotionEvent?): Boolean {
            ev?.let { event ->
                when (event.action) {
                    MotionEvent.ACTION_DOWN -> {
                        startX = event.x
                        startY = event.y
                        isHorizontalScroll = false
                    }
                    MotionEvent.ACTION_MOVE -> {
                        val deltaX = Math.abs(event.x - startX)
                        val deltaY = Math.abs(event.y - startY)
                        
                        // 判断是否为水平滑动
                        if (deltaX > deltaY && deltaX > 10) {
                            isHorizontalScroll = true
                        }
                    }
                }
            }
            return super.onInterceptTouchEvent(ev)
        }

        // NestedScrollingParent3 接口实现
        override fun onStartNestedScroll(child: View, target: View, axes: Int, type: Int): Boolean {
            return parentHelper.onStartNestedScroll(child, target, axes, type)
        }

        override fun onNestedScrollAccepted(child: View, target: View, axes: Int, type: Int) {
            parentHelper.onNestedScrollAccepted(child, target, axes, type)
        }

        override fun onStopNestedScroll(target: View, type: Int) {
            parentHelper.onStopNestedScroll(target, type)
        }

        override fun onNestedScroll(
            target: View,
            dxConsumed: Int,
            dyConsumed: Int,
            dxUnconsumed: Int,
            dyUnconsumed: Int,
            type: Int
        ) {
            parentHelper.onNestedScroll(target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, type)
        }

        override fun onNestedPreScroll(
            target: View,
            dx: Int,
            dy: Int,
            consumed: IntArray,
            type: Int
        ) {
            parentHelper.onNestedPreScroll(target, dx, dy, consumed, type)
        }
    }

    /**
     * 示例3：下拉刷新与列表滚动冲突处理
     * 重写canChildScrollUp方法来判断子View是否可以向上滚动
     */
    class CustomSwipeRefreshLayout @JvmOverloads constructor(
        context: Context,
        attrs: AttributeSet? = null
    ) : androidx.swiperefreshlayout.widget.SwipeRefreshLayout(context, attrs) {

        override fun canChildScrollUp(): Boolean {
            // 检查子View是否可以向上滚动
            val child = getChildAt(0)
            return when (child) {
                is RecyclerView -> {
                    val layoutManager = child.layoutManager
                    when (layoutManager) {
                        is androidx.recyclerview.widget.LinearLayoutManager -> {
                            layoutManager.findFirstCompletelyVisibleItemPosition() > 0
                        }
                        is androidx.recyclerview.widget.GridLayoutManager -> {
                            layoutManager.findFirstCompletelyVisibleItemPosition() > 0
                        }
                        else -> super.canChildScrollUp()
                    }
                }
                else -> super.canChildScrollUp()
            }
        }
    }

    /**
     * 示例4：自定义ViewGroup滑动冲突处理
     * 通过重写触摸事件分发机制来处理滑动冲突
     */
    class CustomScrollViewGroup @JvmOverloads constructor(
        context: Context,
        attrs: AttributeSet? = null,
        defStyleAttr: Int = 0
    ) : FrameLayout(context, attrs, defStyleAttr) {

        private var startX = 0f
        private var startY = 0f
        private var lastX = 0f
        private var lastY = 0f
        private var isScrolling = false
        private val touchSlop = ViewConfiguration.get(context).scaledTouchSlop

        override fun onInterceptTouchEvent(ev: MotionEvent?): Boolean {
            ev?.let { event ->
                when (event.action) {
                    MotionEvent.ACTION_DOWN -> {
                        startX = event.x
                        startY = event.y
                        lastX = startX
                        lastY = startY
                        isScrolling = false
                    }
                    MotionEvent.ACTION_MOVE -> {
                        val deltaX = Math.abs(event.x - startX)
                        val deltaY = Math.abs(event.y - startY)
                        
                        // 判断是否应该拦截触摸事件
                        if (!isScrolling && (deltaX > touchSlop || deltaY > touchSlop)) {
                            isScrolling = true
                        }
                        
                        if (isScrolling) {
                            // 根据滑动方向决定是否拦截
                            return if (deltaX > deltaY) {
                                // 水平滑动，拦截事件
                                true
                            } else {
                                // 垂直滑动，不拦截
                                false
                            }
                        }
                        
                        lastX = event.x
                        lastY = event.y
                    }
                    MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
                        isScrolling = false
                    }
                }
            }
            return super.onInterceptTouchEvent(ev)
        }

        override fun onTouchEvent(event: MotionEvent?): Boolean {
            event?.let { ev ->
                when (ev.action) {
                    MotionEvent.ACTION_MOVE -> {
                        if (isScrolling) {
                            // 处理滑动逻辑
                            val deltaX = ev.x - lastX
                            val deltaY = ev.y - lastY
                            
                            // 这里可以添加具体的滑动处理逻辑
                            // 例如：scrollBy(deltaX.toInt(), deltaY.toInt())
                            
                            lastX = ev.x
                            lastY = ev.y
                            return true
                        }
                    }
                }
            }
            return super.onTouchEvent(event)
        }
    }

    /**
     * 示例5：多指手势冲突处理
     * 通过判断触摸点数量来处理多指手势
     */
    class MultiTouchScrollView @JvmOverloads constructor(
        context: Context,
        attrs: AttributeSet? = null,
        defStyleAttr: Int = 0
    ) : FrameLayout(context, attrs, defStyleAttr) {

        private var pointerCount = 0
        private var isMultiTouch = false

        override fun onInterceptTouchEvent(ev: MotionEvent?): Boolean {
            ev?.let { event ->
                pointerCount = event.pointerCount
                
                when (event.action and MotionEvent.ACTION_MASK) {
                    MotionEvent.ACTION_POINTER_DOWN -> {
                        if (pointerCount > 1) {
                            isMultiTouch = true
                        }
                    }
                    MotionEvent.ACTION_POINTER_UP -> {
                        if (pointerCount <= 1) {
                            isMultiTouch = false
                        }
                    }
                }
                
                // 如果是多指触摸，拦截事件进行特殊处理
                if (isMultiTouch) {
                    return true
                }
            }
            return super.onInterceptTouchEvent(ev)
        }

        override fun onTouchEvent(event: MotionEvent?): Boolean {
            event?.let { ev ->
                if (isMultiTouch) {
                    // 处理多指触摸逻辑
                    when (ev.action and MotionEvent.ACTION_MASK) {
                        MotionEvent.ACTION_MOVE -> {
                            if (pointerCount == 2) {
                                // 双指缩放逻辑
                                handlePinchToZoom(ev)
                            }
                        }
                    }
                    return true
                }
            }
            return super.onTouchEvent(event)
        }

        private fun handlePinchToZoom(event: MotionEvent) {
            // 双指缩放的具体实现
            if (event.pointerCount == 2) {
                val x1 = event.getX(0)
                val y1 = event.getY(0)
                val x2 = event.getX(1)
                val y2 = event.getY(1)
                
                val distance = Math.sqrt(((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)).toDouble())
                // 根据距离变化计算缩放比例
                // 这里可以添加具体的缩放逻辑
            }
        }
    }
}
